package com.zheng.study.company.dao.impl;

import com.zheng.study.base.bean.BaseEnumManager;
import com.zheng.study.base.dao.impl.BaseDaoImpl;
import com.zheng.study.company.dao.DepartmentDao;
import com.zheng.study.company.entity.Company;
import com.zheng.study.company.entity.Department;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * newFile
 * ============================================================================
 * author : dzw
 * createDate:  2018/8/24 。
 * ============================================================================
 */
@Repository
public class DepartmentDaoImpl extends BaseDaoImpl<Department, String> implements DepartmentDao {

	@Override
	public boolean isParentDepartment(Department department) {
		String hql;
		if(department==null){
			hql = "select count(*) from " + Department.class.getName() + " d where d.parent is null and d.state = :state";
			return ((Long) getSession().createQuery(hql).setParameter("state", BaseEnumManager.StateEnum.Enable).uniqueResult()) > 0;
		}else {
			hql = "select count(*) from " + Department.class.getName() + " model where model.parent = :parent and model.state = :state";
			return ((Long) getSession().createQuery(hql).setParameter("parent", department).setParameter("state", BaseEnumManager.StateEnum.Enable).uniqueResult()) > 0;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Department> getRootDepartments(Company company) {
		if(company!=null){
			String hql = "from " + Department.class.getName() + " model where model.company = :company and model.parent is null and model.state = :state order by model.pinYinHead asc ";
			return getSession().createQuery(hql).setParameter("company", company).setParameter("state", BaseEnumManager.StateEnum.Enable).list();
		}else{
			return new ArrayList<Department>();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Department> getDepartments(Company company, Department department) {
		Assert.notNull(company, "company is required");
		Assert.notNull(department, "department is required");
		String hql = "from " + Department.class.getName() + " model where model.company = :company and model.parent = :parent and model.state = :state order by model.pinYinHead asc ";
		return getSession().createQuery(hql).setParameter("company", company).setParameter("parent", department).setParameter("state", BaseEnumManager.StateEnum.Enable).list();
	}

}
